package com.google.code.opengw.server.initializer;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import com.google.code.opengw.server.Constants;
import com.google.code.opengw.server.DataStore;
import com.google.code.opengw.server.Server;
import com.google.code.opengw.server.support.CertificateUtils;
import com.google.code.opengw.support.OpenGWException;

class KeystoreInitializer {

	void initialize() throws NoSuchAlgorithmException, CertificateException,
			IOException, KeyStoreException, OpenGWException {
		DataStore dataStore = DataStore.getInstance();
		Server server = Server.getInstance();
		/*
		 * START OF TRUSTED CERTIFICATES INITIALIZATION
		 */

		final InputStream is = new FileInputStream(server.getKeystore());
		final KeyStore keystore = KeyStore.getInstance(KeyStore
				.getDefaultType());
		keystore.load(is, server.getKeystorePassword()
				.toCharArray());
		final Enumeration<String> keyEnum = keystore.aliases();
		while (keyEnum.hasMoreElements()) {
			X509Certificate certificate = (X509Certificate) keystore
					.getCertificate(keyEnum.nextElement());
			dataStore.addTrustedCertificate(
					CertificateUtils.getCertificateSubjectDNCN(certificate),
					certificate);
		}

		/*
		 * END OF TRUSTED CERTIFICATES INITIALIZATION
		 */
	}
}
